package basic.basic_class04;

/**
 * 已知一棵完全二叉树，求其节点的个数
 */
public class Code_08_CompleteTreeNodeNumber {

    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }

    // 主方法入口
    public static int nodeNum(Node head) {
        if(head == null) return 0;
        int height = getHeight(head,1);
        return bs(head,1,height);
    }

    // 具体实现方法
    private static int bs(Node head, int level, int height) {
        if(level == height) return 1;
        if(getHeight(head.right,level + 1) == height){
            return (1 << (height - level)) + bs(head.right,level+1,height);
        }else{
            return (1 << (height - level - 1)) + bs(head.left,level+1,height);
        }
    }

    // 获取当前树的高度
    private static int getHeight(Node node, int level) {
        while(node != null){
            level++;
            node = node.left;
        }
        return level - 1;
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.left = new Node(2);
        head.right = new Node(3);
        head.left.left = new Node(4);
        head.left.right = new Node(5);
        head.right.left = new Node(6);
        System.out.println(nodeNum(head));
    }
}
